/*
 * Description: 字符串帮助类
 */
#include "string_util.h"
#include <algorithm>
#include <ctime>

namespace {
    const int BUFFER_TIME_VALUE = 100;
}

std::string StringUtil::UpperCase(const std::string& str)
{
    std::string ret = str;
    std::transform(ret.begin(), ret.end(), ret.begin(), ::toupper);
    return ret;
}

std::string StringUtil::WStringToString(const std::wstring& wstr)
{
    int len = static_cast<int>(wstr.length());
    int resultLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), len, nullptr, 0, nullptr, nullptr);
    if (resultLen == 0) {
        return "";
    }
    std::string value(resultLen, '\0');
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), len, const_cast<LPSTR>(value.c_str()),
        resultLen, nullptr, nullptr);
    return value;
}

std::string StringUtil::FormatDateTime(const char* timeFormat, time_t value)
{
    std::string retVal;
    if (value != (static_cast<time_t>(-1))) {
        char buf[BUFFER_TIME_VALUE] = { 0 }; // "%Y-%m-%d %H:%M:%S"
        struct tm newTime = { 0 };
        errno_t err = localtime_s(&newTime, &value);
        if (err == S_OK) {
            if (strftime(buf, BUFFER_TIME_VALUE, timeFormat, &newTime) != 0) { // 写入日期数据
                retVal = buf;
            }
        }
    }
    return retVal;
}
